package yuandaima;
import java.io.*;  
import java.nio.file.*;  
import java.util.*;  
import java.util.regex.*;  
import java.util.stream.*;  
  
public class PriceCalculator {  
    public static void main(String[] args) {  
        String filePath = "D:\\eclipse-java-2024-09-R-win32-x86_64\\10.22\\prices.txt";  
        List<Double> prices = new ArrayList<>();  
  
        try {  
            List<String> lines = Files.readAllLines(Paths.get(filePath));  
              
            Pattern pricePattern = Pattern.compile("(\\d+)元");  
            for (String line : lines) {  
                Matcher matcher = pricePattern.matcher(line);  
                if (matcher.find()) {  
                    prices.add(Double.parseDouble(matcher.group(1)));  
                }  
            }  
  
            double averagePrice = prices.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);  
            System.out.println("平均价格: " + averagePrice + "元");  
            String averagePriceString = String.format("\n平均价格：%.2f元/台\n", averagePrice);  
            Files.write(Paths.get(filePath), averagePriceString.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);  
  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}